package com.keur.money.ui.steps.act

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.keur.money.app.MyApp
import com.keur.money.base.utils.ImageUtil
import com.keur.money.base.utils.TitleBarUtil
import com.keur.money.base.utils.log.MullaLog
import com.keur.money.databinding.ActMullaCameraSelfieBinding
import com.keur.money.http.HttpHelper
import com.keur.money.mvp.MvpAct
import com.keur.money.ui.steps.impl.KeurUploadPresenterImpl
import com.keur.money.ui.steps.view.IKeurUploadView
import com.keur.money.utils.event.KeurEventType
import com.keur.money.utils.helper.KeurCustomConfigsHelper
import com.keur.money.utils.imagecovert.ImageConvert
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/12 17:12
 * @Annotation：自拍照
 */
class KeurCameraSelfieAct: MvpAct<IKeurUploadView, KeurUploadPresenterImpl>(),IKeurUploadView {
    lateinit var binding: ActMullaCameraSelfieBinding

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""

    override fun createPresenter(): KeurUploadPresenterImpl {
        return KeurUploadPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaCameraSelfieBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        binding.titleLayout.setPadding(0, TitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCamera()
    }

    override fun initMullaListener() {
        binding.imgBack.setOnClickListener {
            finish()
        }

        //客服
        binding.imgKefu.setOnClickListener {
            showMullaKefuDialog("SelfieCamera Page")
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CUSTOMER,"SelfieCamera Page")
        }

        //拍照
        binding.imgTakeCamera.setOnClickListener {
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_CAMERA_TAKE_PHOTO,"SelfieCamera Page")
            takeFilePhoto()
        }

        //重拍
        binding.remakeLayout.setOnClickListener {
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_STEP_SELFIE_REMAKE,"")
            showTakeView()
        }

        //使用
        binding.usePhotoLayout.setOnClickListener {
            HttpHelper.addKeurEventAction(KeurEventType.CLICK.KEUR_CLICK_STEP_SELFIE_USE_PHOTO, imgUsePath)
            showMullaLoading(isTOuchOut = false, isCancel = false)
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    MullaLog.e("imageConvert success>>>>>>>$localPath")
                    presenter.onMullaUploadImageAction(localPath)
                }
            }
        }
    }

    override fun initMullaData() {
        //牌照信息
        val licenseInfo = KeurCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /**
     * 打开相机预览
     */
    private fun startCamera() {
        showTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.carmeraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = MyApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    imgUri?.path?.let {
                        MullaLog.e("take photo complete>>>>>>>${it}")
                        imgUsePath = it
                        ImageUtil.instance?.loadImageUrl(this@KeurCameraSelfieAct,binding.imgPreview,imgUsePath,0)
                    }
                    showCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    MullaLog.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showTakeView(){
        binding.imgPreview.visibility = View.GONE
        binding.imgTakeCamera.visibility = View.VISIBLE
        binding.remakeLayout.visibility = View.INVISIBLE
        binding.usePhotoLayout.visibility = View.INVISIBLE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCompleteView(){
        binding.imgPreview.visibility = View.VISIBLE
        binding.imgTakeCamera.visibility = View.INVISIBLE
        binding.remakeLayout.visibility = View.VISIBLE
        binding.usePhotoLayout.visibility = View.VISIBLE
    }

    /**
     * 图片上传完成
     */
    override fun showMullaUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_SELFIE_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addKeurEventAction(KeurEventType.PAGE.KEUR_PAGE_STEP_SELFIE_CAMERA_END)
        if (::cameraExecutor.isInitialized){
            cameraExecutor.shutdown()
        }
    }
}